using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Toolbox.DnsService.Events;
using Toolbox.DnsService.Interfaces;
using Toolbox.DnsService.Models;

namespace Toolbox.DnsService.Services
{
    /// <summary>
    /// 本地DNS服务实现
    /// 作者：huobing
    /// </summary>
    public class LocalDnsService : IDnsService
    {
        #region 字段和属性

        private UdpClient? _udpClient;
        private CancellationTokenSource? _cancellationTokenSource;
        private Task? _listenerTask;
        private bool _isRunning = false;
        private bool _disposed = false;
        private IDnsLogger? _logger;
        private bool _enableLogging = true;
        private readonly ConcurrentDictionary<string, string> _dnsCache = new();
        private readonly ConcurrentDictionary<string, DateTime> _cacheExpiration = new();
        private readonly List<string> _upstreamDnsServers = new();
        private readonly int _port;

        /// <summary>
        /// 获取服务是否正在运行
        /// </summary>
        public bool IsRunning => _isRunning;

        /// <summary>
        /// 获取监听端口
        /// </summary>
        public int Port => _port;

        /// <summary>
        /// 获取DNS缓存记录
        /// </summary>
        public Dictionary<string, string> DnsCache
        {
            get
            {
                CleanExpiredCache();
                return new Dictionary<string, string>(_dnsCache);
            }
        }

        /// <summary>
        /// DNS请求处理事件
        /// </summary>
        public event EventHandler<DnsRequestEventArgs>? DnsRequestProcessed;

        /// <summary>
        /// 服务状态变化事件
        /// </summary>
        public event EventHandler<DnsServiceStatusEventArgs>? StatusChanged;

        #endregion

        #region 构造函数

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="port">监听端口</param>
        /// <param name="upstreamDnsServers">上游DNS服务器列表（逗号分隔）</param>
        public LocalDnsService(int port = 153, string upstreamDnsServers = "8.8.8.8,114.114.114.114")
        {
            _port = port;
            
            // 解析上游DNS服务器
            if (!string.IsNullOrWhiteSpace(upstreamDnsServers))
            {
                var servers = upstreamDnsServers.Split(',', StringSplitOptions.RemoveEmptyEntries);
                foreach (var server in servers)
                {
                    var trimmedServer = server.Trim();
                    if (!string.IsNullOrWhiteSpace(trimmedServer))
                    {
                        _upstreamDnsServers.Add(trimmedServer);
                    }
                }
            }
            
            // 如果没有指定上游DNS服务器，添加默认值
            if (_upstreamDnsServers.Count == 0)
            {
                _upstreamDnsServers.Add("8.8.8.8");
                _upstreamDnsServers.Add("114.114.114.114");
            }
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 启动DNS服务
        /// </summary>
        /// <returns>是否启动成功</returns>
        public bool Start()
        {
            if (_isRunning)
            {
                LogStatus("DNS服务已经在运行中");
                return true;
            }

            try
            {
                // 创建UDP客户端
                _udpClient = new UdpClient(_port);
                _cancellationTokenSource = new CancellationTokenSource();
                
                // 启动监听任务
                _listenerTask = Task.Run(async () => await ListenForDnsRequestsAsync(_cancellationTokenSource.Token));
                
                _isRunning = true;
                
                OnStatusChanged("DNS服务已启动", true);
                LogStatus($"DNS服务已启动，监听端口: {_port}");
                LogStatus($"上游DNS服务器: {string.Join(", ", _upstreamDnsServers)}");
                
                return true;
            }
            catch (Exception ex)
            {
                OnStatusChanged($"启动DNS服务失败: {ex.Message}", false);
                LogError($"启动DNS服务失败: {ex.Message}", ex);
                
                Stop();
                return false;
            }
        }

        /// <summary>
        /// 停止DNS服务
        /// </summary>
        public void Stop()
        {
            if (!_isRunning)
            {
                return;
            }

            try
            {
                _cancellationTokenSource?.Cancel();
                
                // 等待监听任务完成
                if (_listenerTask != null && !_listenerTask.IsCompleted)
                {
                    _listenerTask.Wait(TimeSpan.FromSeconds(5));
                }
                
                _udpClient?.Close();
                _udpClient?.Dispose();
                _cancellationTokenSource?.Dispose();
                
                _isRunning = false;
                
                OnStatusChanged("DNS服务已停止", true);
                LogStatus("DNS服务已停止");
            }
            catch (Exception ex)
            {
                OnStatusChanged($"停止DNS服务时发生错误: {ex.Message}", false);
                LogError($"停止DNS服务时发生错误: {ex.Message}", ex);
            }
            finally
            {
                _udpClient = null;
                _cancellationTokenSource = null;
                _listenerTask = null;
            }
        }

        /// <summary>
        /// 添加DNS记录
        /// </summary>
        /// <param name="domain">域名</param>
        /// <param name="ip">IP地址</param>
        /// <returns>是否添加成功</returns>
        public bool AddDnsRecord(string domain, string ip)
        {
            if (string.IsNullOrWhiteSpace(domain) || string.IsNullOrWhiteSpace(ip))
            {
                return false;
            }

            try
            {
                _dnsCache[domain.ToLower()] = ip;
                _cacheExpiration[domain.ToLower()] = DateTime.Now.AddHours(1);
                
                LogStatus($"添加DNS记录: {domain} -> {ip}");
                return true;
            }
            catch (Exception ex)
            {
                LogError($"添加DNS记录失败: {ex.Message}", ex);
                return false;
            }
        }

        /// <summary>
        /// 移除DNS记录
        /// </summary>
        /// <param name="domain">域名</param>
        /// <returns>是否移除成功</returns>
        public bool RemoveDnsRecord(string domain)
        {
            if (string.IsNullOrWhiteSpace(domain))
            {
                return false;
            }

            try
            {
                var domainKey = domain.ToLower();
                bool removed = _dnsCache.TryRemove(domainKey, out _);
                _cacheExpiration.TryRemove(domainKey, out _);
                
                if (removed)
                {
                    LogStatus($"移除DNS记录: {domain}");
                }
                
                return removed;
            }
            catch (Exception ex)
            {
                LogError($"移除DNS记录失败: {ex.Message}", ex);
                return false;
            }
        }

        /// <summary>
        /// 清除所有DNS记录
        /// </summary>
        public void ClearDnsRecords()
        {
            try
            {
                _dnsCache.Clear();
                _cacheExpiration.Clear();
                
                LogStatus("已清除所有DNS记录");
            }
            catch (Exception ex)
            {
                LogError($"清除DNS记录失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 测试DNS服务器连接
        /// </summary>
        /// <param name="dnsServer">DNS服务器地址</param>
        /// <param name="timeout">超时时间（毫秒）</param>
        /// <returns>测试结果</returns>
        public async Task<DnsTestResult> TestDnsServerAsync(string dnsServer, int timeout = 5000)
        {
            var result = new DnsTestResult { IsSuccess = false };
            
            try
            {
                var stopwatch = Stopwatch.StartNew();
                
                using var ping = new System.Net.NetworkInformation.Ping();
                var reply = await ping.SendPingAsync(dnsServer, timeout);
                
                stopwatch.Stop();
                
                result.ResponseTimeMs = stopwatch.ElapsedMilliseconds;
                result.IsSuccess = reply.Status == System.Net.NetworkInformation.IPStatus.Success;
                
                if (!result.IsSuccess)
                {
                    result.ErrorMessage = $"Ping失败: {reply.Status}";
                }
                
                LogStatus($"测试DNS服务器 {dnsServer}: {(result.IsSuccess ? "成功" : "失败")}，响应时间: {result.ResponseTimeMs}ms");
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
                LogError($"测试DNS服务器 {dnsServer} 失败: {ex.Message}", ex);
            }
            
            return result;
        }

        /// <summary>
        /// 设置日志记录器
        /// </summary>
        /// <param name="logger">日志记录器</param>
        public void SetLogger(IDnsLogger logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 启用日志记录
        /// </summary>
        /// <param name="enable">是否启用</param>
        public void EnableLogging(bool enable)
        {
            _enableLogging = enable;
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 监听DNS请求
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        private async Task ListenForDnsRequestsAsync(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested && _udpClient != null)
            {
                try
                {
                    // 接收UDP数据包
                    var receiveResult = await _udpClient.ReceiveAsync(cancellationToken);
                    
                    // 处理DNS请求
                    _ = Task.Run(async () => await ProcessDnsRequestAsync(receiveResult.Buffer, receiveResult.RemoteEndPoint));
                }
                catch (OperationCanceledException)
                {
                    // 正常取消
                    break;
                }
                catch (Exception ex)
                {
                    LogError($"处理DNS请求时发生错误: {ex.Message}", ex);
                }
            }
        }

        /// <summary>
        /// 处理DNS请求
        /// </summary>
        /// <param name="requestData">请求数据</param>
        /// <param name="remoteEndPoint">远程端点</param>
        private async Task ProcessDnsRequestAsync(byte[] requestData, IPEndPoint remoteEndPoint)
        {
            try
            {
                // 解析DNS请求（简化实现）
                var domain = ExtractDomainFromDnsRequest(requestData);
                
                if (string.IsNullOrWhiteSpace(domain))
                {
                    LogStatus($"收到无效DNS请求，来源: {remoteEndPoint}");
                    return;
                }
                
                LogStatus($"收到DNS查询: {domain}，来源: {remoteEndPoint}");
                
                // 检查缓存
                string? resolvedIp = null;
                if (_dnsCache.TryGetValue(domain.ToLower(), out var cachedIp))
                {
                    resolvedIp = cachedIp;
                    LogStatus($"从缓存解析: {domain} -> {resolvedIp}");
                }
                else
                {
                    // 向上游DNS服务器查询
                    resolvedIp = await QueryUpstreamDnsAsync(domain);
                    
                    if (!string.IsNullOrWhiteSpace(resolvedIp))
                    {
                        // 缓存结果
                        AddDnsRecord(domain, resolvedIp);
                        LogStatus($"向上游DNS查询: {domain} -> {resolvedIp}");
                    }
                }
                
                // 发送响应（简化实现）
                if (!string.IsNullOrWhiteSpace(resolvedIp))
                {
                    var responseData = CreateDnsResponse(requestData, resolvedIp);
                    await _udpClient!.SendAsync(responseData, responseData.Length, remoteEndPoint);
                    
                    OnDnsRequestProcessed(domain, resolvedIp, remoteEndPoint.Address.ToString());
                    LogStatus($"发送DNS响应: {domain} -> {resolvedIp}");
                }
                else
                {
                    LogStatus($"无法解析域名: {domain}");
                }
            }
            catch (Exception ex)
            {
                LogError($"处理DNS请求时发生错误: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 从DNS请求中提取域名
        /// </summary>
        /// <param name="requestData">请求数据</param>
        /// <returns>域名</returns>
        private string ExtractDomainFromDnsRequest(byte[] requestData)
        {
            try
            {
                // 简化实现：假设请求格式为标准的DNS查询
                if (requestData.Length < 12) return string.Empty;
                
                var domainParts = new List<string>();
                int position = 12; // 跳过DNS头部
                
                while (position < requestData.Length && requestData[position] != 0)
                {
                    int length = requestData[position];
                    position++;
                    
                    if (position + length > requestData.Length) break;
                    
                    var part = Encoding.UTF8.GetString(requestData, position, length);
                    domainParts.Add(part);
                    position += length;
                }
                
                return string.Join(".", domainParts);
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 向上游DNS服务器查询
        /// </summary>
        /// <param name="domain">域名</param>
        /// <returns>解析的IP地址</returns>
        private async Task<string?> QueryUpstreamDnsAsync(string domain)
        {
            foreach (var dnsServer in _upstreamDnsServers)
            {
                try
                {
                    // 使用指定的DNS服务器进行查询
                    using var dnsClient = new System.Net.Sockets.UdpClient();
                    
                    // 创建DNS查询数据包
                    var queryData = CreateDnsQuery(domain);
                    
                    // 发送查询到指定的DNS服务器
                    var dnsEndPoint = new IPEndPoint(IPAddress.Parse(dnsServer), 53);
                    await dnsClient.SendAsync(queryData, queryData.Length, dnsEndPoint);
                    
                    // 接收响应（设置超时）
                    var receiveTask = dnsClient.ReceiveAsync();
                    var timeoutTask = Task.Delay(TimeSpan.FromSeconds(5));
                    
                    var completedTask = await Task.WhenAny(receiveTask, timeoutTask);
                    
                    if (completedTask == receiveTask)
                    {
                        var response = receiveTask.Result;
                        var ipAddress = ExtractIpFromDnsResponse(response.Buffer);
                        
                        if (!string.IsNullOrWhiteSpace(ipAddress))
                        {
                            return ipAddress;
                        }
                    }
                    else
                    {
                        LogError($"向上游DNS服务器 {dnsServer} 查询 {domain} 超时");
                    }
                }
                catch (Exception ex)
                {
                    LogError($"向上游DNS服务器 {dnsServer} 查询 {domain} 失败: {ex.Message}");
                }
            }
            
            return null;
        }

        /// <summary>
        /// 创建DNS查询数据包
        /// </summary>
        /// <param name="domain">域名</param>
        /// <returns>DNS查询数据</returns>
        private byte[] CreateDnsQuery(string domain)
        {
            var query = new List<byte>();
            
            // 事务ID (随机)
            var random = new Random();
            query.Add((byte)random.Next(0, 256));
            query.Add((byte)random.Next(0, 256));
            
            // 标志：标准查询，递归查询
            query.Add(0x01); // QR=0, OPCODE=0, AA=0, TC=0, RD=1
            query.Add(0x00); // RA=0, Z=0, RCODE=0
            
            // 问题数量 = 1
            query.Add(0x00);
            query.Add(0x01);
            
            // 回答数量 = 0
            query.Add(0x00);
            query.Add(0x00);
            
            // 权威记录数量 = 0
            query.Add(0x00);
            query.Add(0x00);
            
            // 附加记录数量 = 0
            query.Add(0x00);
            query.Add(0x00);
            
            // 域名部分
            var domainParts = domain.Split('.');
            foreach (var part in domainParts)
            {
                query.Add((byte)part.Length);
                query.AddRange(Encoding.UTF8.GetBytes(part));
            }
            query.Add(0x00); // 域名结束
            
            // 查询类型 A记录 = 1
            query.Add(0x00);
            query.Add(0x01);
            
            // 查询类 IN = 1
            query.Add(0x00);
            query.Add(0x01);
            
            return query.ToArray();
        }

        /// <summary>
        /// 从DNS响应中提取IP地址
        /// </summary>
        /// <param name="responseData">响应数据</param>
        /// <returns>IP地址</returns>
        private string? ExtractIpFromDnsResponse(byte[] responseData)
        {
            try
            {
                if (responseData.Length < 12) return null;
                
                // 检查响应码
                var rcode = responseData[3] & 0x0F;
                if (rcode != 0) return null; // 非零表示错误
                
                // 获取回答数量
                var answerCount = (responseData[6] << 8) | responseData[7];
                if (answerCount == 0) return null;
                
                // 跳过问题部分
                int position = 12;
                while (position < responseData.Length && responseData[position] != 0)
                {
                    int length = responseData[position];
                    position += length + 1;
                }
                position += 5; // 跳过结束的0和QType、QClass
                
                // 查找A记录
                for (int i = 0; i < answerCount && position < responseData.Length - 10; i++)
                {
                    // 跳过域名指针（2字节）
                    if (responseData[position] == 0xC0)
                    {
                        position += 2;
                    }
                    else
                    {
                        // 跳过域名
                        while (position < responseData.Length && responseData[position] != 0)
                        {
                            int length = responseData[position];
                            position += length + 1;
                        }
                        position++; // 跳过结束的0
                    }
                    
                    // 检查记录类型
                    var type = (responseData[position] << 8) | responseData[position + 1];
                    position += 2;
                    
                    // 跳过类
                    position += 2;
                    
                    // 跳过TTL
                    position += 4;
                    
                    // 获取数据长度
                    var dataLength = (responseData[position] << 8) | responseData[position + 1];
                    position += 2;
                    
                    if (type == 1 && dataLength == 4) // A记录，IPv4地址
                    {
                        // 提取IP地址
                        var ipBytes = responseData[position..(position + 4)];
                        return new IPAddress(ipBytes).ToString();
                    }
                    
                    position += dataLength;
                }
            }
            catch (Exception ex)
            {
                LogError($"从DNS响应提取IP地址失败: {ex.Message}");
            }
            
            return null;
        }

        /// <summary>
        /// 创建DNS响应
        /// </summary>
        /// <param name="requestData">请求数据</param>
        /// <param name="ipAddress">IP地址</param>
        /// <returns>响应数据</returns>
        private byte[] CreateDnsResponse(byte[] requestData, string ipAddress)
        {
            try
            {
                // 解析IP地址
                var ipBytes = IPAddress.Parse(ipAddress).GetAddressBytes();
                
                // 创建响应列表
                var response = new List<byte>();
                
                // 复制请求头部（事务ID）
                response.AddRange(requestData[0..2]);
                
                // 设置响应标志（设置AA=1表示权威应答）
                response.Add(0x85); // QR=1, OPCODE=0, AA=1, TC=0, RD=1
                response.Add(0x80); // RA=1, Z=0, RCODE=0
                
                // 问题数量（从请求中复制）
                response.AddRange(requestData[4..6]);
                
                // 回答数量 = 1
                response.Add(0x00);
                response.Add(0x01);
                
                // 权威记录数量 = 1（添加SOA记录）
                response.Add(0x00);
                response.Add(0x01);
                
                // 附加记录数量 = 0
                response.Add(0x00);
                response.Add(0x00);
                
                // 复制问题部分（域名查询部分）
                int questionStart = 12;
                int questionEnd = questionStart;
                
                // 找到问题部分的结束位置
                while (questionEnd < requestData.Length && requestData[questionEnd] != 0)
                {
                    int length = requestData[questionEnd];
                    questionEnd += length + 1;
                }
                questionEnd += 5; // 包括结束的0和QType、QClass
                
                if (questionEnd <= requestData.Length)
                {
                    response.AddRange(requestData[questionStart..questionEnd]);
                }
                
                // 添加回答记录
                // 指针到问题部分的域名（0xC0 0x0C）
                response.Add(0xC0);
                response.Add(0x0C);
                
                // 类型 A记录 = 1
                response.Add(0x00);
                response.Add(0x01);
                
                // 类 IN = 1
                response.Add(0x00);
                response.Add(0x01);
                
                // TTL = 300秒
                response.Add(0x00);
                response.Add(0x00);
                response.Add(0x01);
                response.Add(0x2C);
                
                // 数据长度 = 4（IPv4地址）
                response.Add(0x00);
                response.Add(0x04);
                
                // IP地址
                response.AddRange(ipBytes);
                
                // 添加权威记录（SOA记录，显示服务器名dns.local）
                // 指针到问题部分的域名（0xC0 0x0C）
                response.Add(0xC0);
                response.Add(0x0C);
                
                // 类型 SOA记录 = 6
                response.Add(0x00);
                response.Add(0x06);
                
                // 类 IN = 1
                response.Add(0x00);
                response.Add(0x01);
                
                // TTL = 300秒
                response.Add(0x00);
                response.Add(0x00);
                response.Add(0x01);
                response.Add(0x2C);
                
                // 数据长度（计算SOA记录数据长度）
                // SOA记录包含：主DNS服务器名、管理员邮箱、序列号、刷新间隔、重试间隔、过期时间、最小TTL
                var soaData = CreateSoaRecordData("dns.local", "admin.dns.local");
                response.Add((byte)(soaData.Length >> 8));
                response.Add((byte)soaData.Length);
                
                // SOA记录数据
                response.AddRange(soaData);
                
                return response.ToArray();
            }
            catch (Exception ex)
            {
                LogError($"创建DNS响应失败: {ex.Message}", ex);
                
                // 返回一个基本的错误响应
                var basicResponse = new List<byte>();
                basicResponse.AddRange(requestData[0..2]); // 事务ID
                basicResponse.Add(0x81); // QR=1
                basicResponse.Add(0x83); // RCODE=3（域名不存在）
                basicResponse.AddRange(new byte[10]); // 其他字段设为0
                return basicResponse.ToArray();
            }
        }

        /// <summary>
        /// 创建SOA记录数据
        /// </summary>
        /// <param name="primaryNameServer">主DNS服务器名</param>
        /// <param name="responsiblePerson">负责人邮箱</param>
        /// <returns>SOA记录数据</returns>
        private byte[] CreateSoaRecordData(string primaryNameServer, string responsiblePerson)
        {
            var soaData = new List<byte>();
            
            // 主DNS服务器名（dns.local）
            var primaryParts = primaryNameServer.Split('.');
            foreach (var part in primaryParts)
            {
                soaData.Add((byte)part.Length);
                soaData.AddRange(Encoding.UTF8.GetBytes(part));
            }
            soaData.Add(0x00); // 结束
            
            // 负责人邮箱（admin.dns.local）
            var personParts = responsiblePerson.Split('.');
            foreach (var part in personParts)
            {
                soaData.Add((byte)part.Length);
                soaData.AddRange(Encoding.UTF8.GetBytes(part));
            }
            soaData.Add(0x00); // 结束
            
            // 序列号 = 1
            soaData.Add(0x00);
            soaData.Add(0x00);
            soaData.Add(0x00);
            soaData.Add(0x01);
            
            // 刷新间隔 = 3600秒（1小时）
            soaData.Add(0x00);
            soaData.Add(0x00);
            soaData.Add(0x0E);
            soaData.Add(0x10);
            
            // 重试间隔 = 600秒（10分钟）
            soaData.Add(0x00);
            soaData.Add(0x00);
            soaData.Add(0x02);
            soaData.Add(0x58);
            
            // 过期时间 = 86400秒（1天）
            soaData.Add(0x00);
            soaData.Add(0x01);
            soaData.Add(0x51);
            soaData.Add(0x80);
            
            // 最小TTL = 300秒
            soaData.Add(0x00);
            soaData.Add(0x00);
            soaData.Add(0x01);
            soaData.Add(0x2C);
            
            return soaData.ToArray();
        }

        /// <summary>
        /// 清理过期缓存
        /// </summary>
        private void CleanExpiredCache()
        {
            var now = DateTime.Now;
            var expiredDomains = new List<string>();
            
            foreach (var kvp in _cacheExpiration)
            {
                if (kvp.Value < now)
                {
                    expiredDomains.Add(kvp.Key);
                }
            }
            
            foreach (var domain in expiredDomains)
            {
                _dnsCache.TryRemove(domain, out _);
                _cacheExpiration.TryRemove(domain, out _);
            }
        }

        /// <summary>
        /// 记录状态信息
        /// </summary>
        /// <param name="message">消息内容</param>
        private void LogStatus(string message)
        {
            if (_enableLogging)
            {
                _logger?.LogStatus(message);
            }
        }

        /// <summary>
        /// 记录错误信息
        /// </summary>
        /// <param name="message">错误消息</param>
        /// <param name="exception">异常对象</param>
        private void LogError(string message, Exception? exception = null)
        {
            if (_enableLogging)
            {
                _logger?.LogError(message, exception);
            }
        }

        /// <summary>
        /// 触发DNS请求处理事件
        /// </summary>
        /// <param name="domain">域名</param>
        /// <param name="resolvedIp">解析的IP地址</param>
        /// <param name="sourceIp">来源IP</param>
        /// <param name="isCached">是否来自缓存</param>
        /// <param name="remoteEndPoint">远程端点</param>
        private void OnDnsRequestProcessed(string domain, string resolvedIp, string sourceIp, bool isCached = false, System.Net.IPEndPoint? remoteEndPoint = null)
        {
            DnsRequestProcessed?.Invoke(this, new DnsRequestEventArgs(domain, resolvedIp, sourceIp, isCached, remoteEndPoint));
        }

        /// <summary>
        /// 触发状态变化事件
        /// </summary>
        /// <param name="message">状态消息</param>
        /// <param name="isSuccess">是否成功</param>
        private void OnStatusChanged(string message, bool isSuccess)
        {
            StatusChanged?.Invoke(this, new DnsServiceStatusEventArgs(message, isSuccess));
        }

        #endregion

        #region IDisposable 实现

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="disposing">是否释放托管资源</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    Stop();
                    _logger?.Dispose();
                }
                
                _disposed = true;
            }
        }

        #endregion
    }
}